#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "functions.h"
#include "tokens.h"


int main(int argc, char *argv[])
{
	char hostname[128];
	char curWorkDir[1024];
	char * pUsername = (char *) malloc(sizeof(char)*1024);
    int a = 0;
    int command_found=0;
	FUNC_TYPE func_return = 0;

    char *tokens[50]={0};
    char *setshell[3]={0};
	int *num_tokens = (int *) malloc(sizeof(int));
	unsigned int cmd;


	//initialize shell environmental variable
	getcwd(curWorkDir, sizeof(curWorkDir));
	setshell[0] = (char *) malloc(sizeof(char)*1024);
	setshell[1] = (char *) malloc(sizeof(char)*1024);
	setshell[2] = (char *) malloc(sizeof(char)*1024);
	setshell[1] = "shell";
	setshell[2] = curWorkDir;
	strcat(setshell[2],"/gbsh");
	setenv_func(2,setshell);

	//fill envp for external commands
	envp[0] = (char *) malloc(sizeof(char)*1024);
	strcat(envp[0], "parent=");
	strcat(envp[0], curWorkDir);
	strcat(envp[0],"/gbsh");
	envp[1] = (char *) 0;

	do{
		gethostname(hostname, sizeof(hostname));
	    getcwd(curWorkDir, sizeof(curWorkDir));
        pUsername = getenv("USERNAME");

		printf("%s@%s %s > ",pUsername,hostname,curWorkDir);

	    cmd = get_tokens(num_tokens, tokens);
		if (cmd == 69) {
			func_return = pipetrial_func(*num_tokens, tokens);

		} else if (cmd == 31) {
			func_return = background_func(*num_tokens, tokens);

		} else  {
			if(tokens[0]!=NULL){
			 command_found=0;
	    	 for(a=0;a<8;a++)
	    	 {
	    		if(!strcmp(tokens[0],mainCommandList[a].CommandName)){
	    			command_found=1;
	    			if (mainCommandList[a].FunctionName != API_PTR) 
	    			{
	    				func_return = mainCommandList[a].FunctionName(*num_tokens, tokens);
	    				break;
	    			}

	    		}
	    	 }

	    	 if(command_found==0) {
	    			external_func(*num_tokens, tokens);
	    	 }
			}
		}

	} while( func_return != -2 );

	printf("- Ahh!! Exiting the awesome gbsh shell!! Goodbye!!\n");

	return 0;
}

